package com.vincce.fitness.core.interceptor;

import com.vincce.fitness.api.UserService;
import com.vincce.fitness.api.WechatRunner;
import com.vincce.fitness.core.base.UserSessionHolder;
import com.vincce.fitness.core.util.AccountUtil;
import com.vincce.fitness.core.util.CheckUtil;
import com.vincce.fitness.core.util.EndecodeUtil;
import com.vincce.fitness.entity.Account;
import com.vincce.fitness.entity.User;
import com.vincce.fitness.entity.UserSession;
import com.vincce.fitness.mappers.core.UserMapper;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by henry on 5/5/14.
 */
public class WechatOauthInterceptor extends HandlerInterceptorAdapter {

	@Resource
	UserMapper userMapper;

	@Resource
	WechatRunner wechatRunner;

	@Resource
	UserService userService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		UserSession userSession = new UserSession();
		if (!CheckUtil.isEmpty(request.getParameter("state"))) {
			String code = request.getParameter("code");
			String billno = request.getParameter("billno");
			if (CheckUtil.isEmpty(code)||CheckUtil.isEmpty(billno)) {
				throw new RuntimeException("Wechat Oauth Failed!");
			} else {
				String accountNo = EndecodeUtil.decode(billno);
				Account account = AccountUtil.map.get(accountNo);
				String openId = wechatRunner.fetchOauthOpenId(code,account);
                if(!CheckUtil.isEmpty(openId)) {
                    userSession.setOpenId(openId);
	                User user = userService.insertOrUpdate(openId, accountNo);
	                userSession.setUserId(user.getId());
                }
			}
		}
		UserSessionHolder.put(userSession);
		return super.preHandle(request, response, handler);
	}
}
